﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using YJTShiftManagement.Events;
using YJTShiftManagement.Models;
using YJTShiftManagement.Service;

namespace YJTShiftManagement
{
    public partial class DoctorShiftViews : UIPage
    {
        private Dictionary<string, string> keyValues = new Dictionary<string, string>();
        private string _currentParameter;
        private string doc_id = "";
        public DoctorShiftViews(string doc_id)
        {
            InitializeComponent();
            BeginDate.Value = DateTime.Now;
            EndDate.Value = DateTime.Now.AddMonths(1);
            // 绑定事件
            BeginDate.ValueChanged += BeginDate_ValueChanged;
            EndDate.ValueChanged += EndDate_ValueChanged;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            dataGridView1.RowHeadersVisible = false;
            this.doc_id = doc_id;
            DoccomboBox.DisplayMember = "Name";
            InitDocList();
        }
        private void BeginDate_ValueChanged(object sender, DateTime value)
        {
            if (EndDate.Value < BeginDate.Value)
            {
                EndDate.Value = BeginDate.Value.AddMonths(1);
            }
            else if (EndDate.Value > BeginDate.Value.AddMonths(1))
            {
                EndDate.Value = BeginDate.Value.AddMonths(1);
            }
        }
        private void EndDate_ValueChanged(object sender, DateTime value)
        {
            DateTime maxEndDate = BeginDate.Value.AddMonths(1);
            if (EndDate.Value > maxEndDate)
            {
                EndDate.Value = maxEndDate;
            }
        }
        public void SetParameter(string parameter)
        {
            // 保存参数（如果需要后续使用）
            _currentParameter = parameter;

            // 更新界面控件或逻辑
            UpdateUI(parameter);
        }
        private void UpdateUI(string parameter)
        {
            // 或者触发数据加载逻辑
            LoadData(parameter);
        }
        private void LoadData(string parameter)
        {
            doc_id = parameter;
            foreach (var item in DoccomboBox.Items)
            {
                // 将item转换为MyItem类型
                if (item is UIComboBox myItem && myItem.Tag is doc_lists asd && asd.doc_id == parameter)
                {
                    DoccomboBox.SelectedItem = myItem;
                    break; // 找到后跳出循环
                }
            }
            InitDataGridView();
        }
        private void InitDocList()
        {
            var request = new { client = "zm_hospital" };
            var result = BaseService.HttpService("api_back/api_scheduling/doc_list", request);

            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
            {
                var data = JsonConvert.DeserializeObject<List<doc_lists>>(result.data.ToString());
                foreach (var item in data)
                {
                    UIComboBox uICombo = new UIComboBox();
                    uICombo.Tag = item;
                    uICombo.Name = item.doc_name;
                    DoccomboBox.Items.Add(uICombo);
                }
            }
            else
            {
                this.ShowErrorDialog(result.msg);
                if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                return;
            }
        }
        static List<string> GetNonEmptyFieldNames(bodys data)
        {
            List<string> fieldNames = new List<string>();

            // Get all properties of the class
            var properties = typeof(bodys).GetProperties();

            // Iterate through each property
            foreach (var property in properties)
            {
                // Get the value of the property
                var value = property.GetValue(data);

                // If the value is not null, add the field name to the list
                if (value != null)
                {
                    fieldNames.Add(property.Name);
                }
            }

            return fieldNames;
        }
        private void AddDateColumn(string fieldName, string headerText)
        {
            // 创建带特殊样式的列
            var column = new DataGridViewTextBoxColumn
            {
                Name = fieldName,
                HeaderText = ValidateDateFormat(headerText),
                DataPropertyName = fieldName,
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Format = "yyyy-MM-dd",
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    BackColor = Color.Lavender
                },
                HeaderCell = new DataGridViewColumnHeaderCell
                {
                    Style = new DataGridViewCellStyle
                    {
                        BackColor = Color.SteelBlue,
                        ForeColor = Color.White,
                        Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold),

                    }
                },
                Width = 100,
            };

            dataGridView1.Columns.Add(column);
        }
        public void AutoAdjustRowHeights()
        {
            // 自动计算所有行高度
            dataGridView1.AutoResizeRows(
                DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders
            );

            // 添加额外行高余量
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Height = (int)(row.Height * 1.2); // 增加20%高度余量
                row.MinimumHeight = row.Height;      // 锁定最小高度
            }

            // 设置标题行高度
            dataGridView1.ColumnHeadersHeightSizeMode =
                DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dataGridView1.ColumnHeadersHeight = 40; // 自定义标题高度
        }
        private string ValidateDateFormat(string dateTitle)
        {
            // 验证日期格式并高亮错误
            var match = Regex.Match(dateTitle, @"（(\d{2}\.\d{2})）$");
            if (!match.Success)
            {
                //Logger.Warn($"非标准日期格式：{dateTitle}");
                return $"{dateTitle}⚠️"; // 添加错误标识
            }

            try
            {
                var dateStr = $"2023-{match.Groups[1].Value.Replace('.', '-')}";
                DateTime.Parse(dateStr);
                return dateTitle;
            }
            catch
            {
                //Logger.Error($"无效日期：{dateTitle}");
                return $"{dateTitle}❌"; // 添加错误标识
            }
        }

        private void InitHeadr(titles[] data)
        {
            JArray dateItems = JArray.FromObject(data);

            dataGridView1.Columns.Clear();

            // 4. 清空现有列（保留非日期列）
            var columnsToRemove = dataGridView1.Columns.Cast<DataGridViewColumn>()
                .Where(c => c.Name.StartsWith("date_title"))
                .ToList();

            foreach (var col in columnsToRemove)
            {
                dataGridView1.Columns.Remove(col);
            }
            AddDateColumn("", "");
            // 5. 添加日期列
            foreach (var item in dateItems)
            {
                AddDateColumn(
                    $"{item["start"]?.ToString()}\n\r{item["end"]?.ToString()}",
                    item["time"]?.ToString()
                );

                if (!keyValues.ContainsKey(item["time"]?.ToString()))
                {
                    keyValues[item["time"]?.ToString()] = $"{item["start"]?.ToString()}\n\r{item["end"]?.ToString()}";
                }
            }
        }
        private void InitDataGridView()
        {
            string BeginDateStr = "";
            string EndDateStr = "";
            if (DateTime.TryParse(BeginDate.Text, out DateTime beginDate))
            {
                BeginDateStr = beginDate.ToString("yyyy-MM-dd");
            }
            if (DateTime.TryParse(EndDate.Text, out DateTime endDate))
            {
                EndDateStr = endDate.ToString("yyyy-MM-dd");
            }
            if (doc_id == null && DoccomboBox.SelectedItem == null)
            {
                this.ShowErrorDialog("请选择医生！");
                return;
            }
            if (DoccomboBox.SelectedItem is UIComboBox)
            {
                var datas = (DoccomboBox.SelectedItem as UIComboBox);
                var iis = (doc_lists)datas.Tag;
                var request = new { start_date = BeginDateStr, end_date = EndDateStr, doc_id = iis.doc_id };
                var result = BaseService.HttpService("api_back/api_scheduling/single_doc_record_view", request);

                if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                {
                    var data = JsonConvert.DeserializeObject<doctorView>(result.data.ToString());
                    InitHeadr(data.title);
                    List<Dictionary<string, object>> rowDataList = new List<Dictionary<string, object>>();
                    if (data.body.Count() > 0)
                    {
                        foreach (var obj in data.body)
                        {
                            // 5. 为每行创建一个字典存储单元格值
                            Dictionary<string, object> rowData = new Dictionary<string, object>();

                            // 6. 填充固定列（如"医生"）
                            rowData[""] = obj.date;

                            // 7. 动态处理其他字段
                            foreach (var item in GetNonEmptyFieldNames(obj))
                            {
                                PropertyInfo propertyInfo = obj.GetType().GetProperty(item);
                                if (propertyInfo != null && item != "date" && keyValues.ContainsKey(item))
                                {
                                    var fieldValue = propertyInfo.GetValue(obj);
                                    string columnName = keyValues[item]; // 假设 keyValues 映射字段到列名
                                    rowData[columnName] = fieldValue;
                                }
                            }

                            // 8. 将单行数据加入列表
                            rowDataList.Add(rowData);
                        }

                        // 9. 批量绑定数据到 DataGridView
                        BindDataToGrid(rowDataList);
                    }
                }
                else
                {
                    this.ShowErrorDialog(result.msg);
                    if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                    return;
                }
                 
            }
        }
        private void BindDataToGrid(List<Dictionary<string, object>> rowDataList)
        {
            dataGridView1.Rows.Clear();


            // 批量添加行
            for (int i = 0; i < rowDataList.Count; i++)
            {
                var rowData = rowDataList[i];
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView1);

                // 按列顺序填充值
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    if (rowData.TryGetValue(column.HeaderText, out object value))
                    {
                        row.Cells[column.Index].Value = value;
                    }
                }

                // 设置Tag为原始对象
                if (i < rowDataList.Count)
                {
                    row.Tag = rowDataList[i];
                }

                dataGridView1.Rows.Add(row);
            }
        }
        private void QueryButton_Click(object sender, EventArgs e)
        {
            InitDataGridView();
        }

       
    }
}
